package cn.tedu.zx.album.adapter.impl;


import cn.tedu.zx.album.adapter.mapper.AlbumMapper;
import cn.tedu.zx.album.adapter.mapper.PictureMapper;
import cn.tedu.zx.album.service.AlbumService;
import cn.tedu.zx.common.exception.ServiceException;
import cn.tedu.zx.common.restful.JsonPage;
import cn.tedu.zx.common.restful.ResponseCode;
import cn.tedu.zx.pojo.court.dto.AlbumAddNewDto;
import cn.tedu.zx.pojo.court.dto.AlbumUpdateDto;
import cn.tedu.zx.pojo.court.entity.Album;
import cn.tedu.zx.pojo.court.entity.Picture;
import cn.tedu.zx.pojo.court.vo.AlbumDetailsVo;
import cn.tedu.zx.pojo.court.vo.AlbumListVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class AlbumServiceImpl implements AlbumService {
    private String message = null;
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private PictureMapper pictureMapper;

    Album album = new Album();

    @Override
    public void addNew(AlbumAddNewDto albumAddNewDto) {
        log.debug("往相册添加文件");

        //检查数据冲突情况
        checkConflict(albumAddNewDto.getName(), 0L);


        BeanUtils.copyProperties(albumAddNewDto, album);
        album.setCreated(LocalDateTime.now());
        album.setUpdated(LocalDateTime.now());
        log.trace("往数据库添加子项：{}", album);
        int insert = albumMapper.insert(album);

        //检查操作是否全部成功
        operateFailed(insert);

        log.trace("{}添加完成", album);
    }


    @Override
    public void deleteById(Long id) {
        log.debug("{}", id);

        //检查相册数据是否存在
        checkEmpty(id);

        /*相片下是否存在关联数据*/
        QueryWrapper<Picture> pictureWrapper = new QueryWrapper();
        pictureWrapper.eq("album_id", id);
        int countByAlbumId = pictureMapper.selectCount(pictureWrapper);
        if (countByAlbumId > 0) {
            message = "删除相册失败，相片下存在关联数据";
            log.warn(message);
            throw new ServiceException(ResponseCode.CONFLICT, message);
        }

        int delete = albumMapper.deleteById(id);

        //检查操作是否全部成功
        operateFailed(delete);
    }

    @Override
    public void updateById(AlbumUpdateDto albumUpdateDto) {
        log.debug("{}", albumUpdateDto);

        //检查数据是否存在
        checkEmpty(albumUpdateDto.getId());

        //检查数据冲突情况
        checkConflict(albumUpdateDto.getName(), albumUpdateDto.getId());

        BeanUtils.copyProperties(albumUpdateDto, album);
        album.setUpdated(LocalDateTime.now());
        log.trace("往数据库修改子项：{}", album);
        int updateById = albumMapper.updateById(album);

//        检查操作是否全部成功
        operateFailed(updateById);
        log.trace("{}修改完成", album);
    }

    @Override
    public AlbumDetailsVo selectDetailsById(Long id) {
        log.debug("传入的id：{}", id);
        AlbumDetailsVo albumDetailsVO = albumMapper.selectDetailsById(id);
        log.debug("查到的数据：{}", albumDetailsVO);
        if (albumDetailsVO == null) {
            message = "查询失败，根据【id=" + id + "】查询的相册详情不存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
        return albumDetailsVO;
    }

    @Override
    public JsonPage<AlbumListVo> list(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AlbumListVo> list = albumMapper.listAlbum();
        PageInfo<AlbumListVo> pageInfo = new PageInfo(list);
        return JsonPage.restPage(pageInfo);
    }

    /**
     * 通过id检查数据是否存在
     * @param id
     */
    private void checkEmpty(Long id) {
        QueryWrapper<Album> albumWrapper = new QueryWrapper();
        albumWrapper.eq("id", id);
        int countById = albumMapper.selectCount(albumWrapper);
        if (countById == 0) {
            message = "操作失败，数据不存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
    }

    /**
     * 文件操作是否与预测一致
     * @param operatedRows
     */
    private void operateFailed(Integer operatedRows) {
        if (operatedRows < 1) {
            String message = "服务器忙,请稍后再试";
            throw new ServiceException(ResponseCode.INTERNAL_SERVER_ERROR, message);
        }
    }


    /**
     * 通过名称字段及id检查内容是否冲突
     * @param name
     * @param id
     */
    private void checkConflict(String name, Long id) {
        QueryWrapper<Album> categoryWrapper = new QueryWrapper();
        categoryWrapper.eq("name", name).ne("id", id);
        int countByName = albumMapper.selectCount(categoryWrapper);
        log.debug("查询数据{}", countByName);
        if (countByName > 0) {
            message = "操作失败，相册名已占用";
            log.warn(message);
            throw new ServiceException(ResponseCode.CONFLICT, message);
        }
    }

}
